package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.redis.RedisCache;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.JsonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCategory;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallSchool;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.HomeCacheManager;
import org.linlinjava.litemall.wx.service.WxGrouponRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 首页服务
 */
@RestController
@RequestMapping("/wx/home")
@Validated
public class WxHomeController {
	private final Log logger = LogFactory.getLog(WxHomeController.class);

	@Autowired
	private LitemallAdService adService;

	@Autowired
	private LitemallGoodsService goodsService;

	@Autowired
	private LitemallBrandService brandService;

	@Autowired
	private LitemallTopicService topicService;

	@Autowired
	private LitemallCategoryService categoryService;

	@Autowired
	private WxGrouponRuleService grouponService;

	@Autowired
	private LitemallCouponService couponService;

	@Autowired
	private LitemallShopService shopService;
	@Autowired
	private LitemallSchoolService schoolService;
	@Autowired
	private NotifyService notifyService;
	@Autowired
	private RedisCache redisCache;
	@Autowired
	private IdentityCardService IdentityCardService;
    @Autowired
    private LitemallSystemConfigService systemConfigService;
	
	
	
	@Autowired
	private LitemallCategorySupportService categorySupportService;

	private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(9);

	private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

	private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(9, 9, 1000, TimeUnit.MILLISECONDS,
			WORK_QUEUE, HANDLER);

	@GetMapping("/cache")
	public Object cache(@NotNull String key) {
		if (!key.equals("litemall_cache")) {
			return ResponseUtil.fail();
		}

		// 清除缓存
		HomeCacheManager.clearAll();
		return ResponseUtil.ok("缓存已清除");
	}

	@GetMapping("/schoolType_new")
	public Object cache2(String cacheKey) {
		/*
		if(StringUtils.isEmpty(cacheKey)) {
			cacheKey = "schoolType_new_1";
		}*/
		// 清除缓存
		//HomeCacheManager.clear(cacheKey);
		redisCache.deleteObject("schoolType_new_1");
		redisCache.deleteObject("schoolType_new_2");
		redisCache.deleteObject("schoolType_new_3");
		return ResponseUtil.ok("缓存已清除");
	}

	@GetMapping("/deleteRedisCache")
	public void deleteRedisCache(Integer shopId) {
		//清除店铺信息
		redisCache.deleteObject("shop_info_"+shopId);
		//清除店铺商品信息
		redisCache.deleteObject("Catalog_info_"+shopId);
	}
	/**
	 * 首页数据
	 * 
	 * @param SchoolId
	 * @return 首页数据
	 */
	@GetMapping("/index")
	public Object index(Integer schoolId, String schoolType) {

		//notifyService.pushPrintOrderInfo(32, "20210601919158", "#1");
		/*
        try {
            // 同时支持Excel 2003、2007
            File excelFile = new File("F:\\b.xlsx"); // 创建文件对象
            FileInputStream is = new FileInputStream(excelFile); // 文件流
            Workbook wb = WorkbookFactory.create(is); // 这种方式 Excel
            IdentityCardService.readExcel(wb, 0, 1, 0);
 
        } catch (Exception e) {
            e.printStackTrace();
        }*/
		
		//redisCache.incr(shop,1);
		// 优先从缓存中读取
		String cacheKey = "schoolType_new_"+schoolId;
		
		/*
		if (HomeCacheManager.hasData(cacheKey)) {
			return ResponseUtil.ok(HomeCacheManager.getCacheData(cacheKey));
		}*/
		if (redisCache.hasData(cacheKey)) {
			//System.out.println("获取缓存数据！");
			String json = redisCache.getCacheObject(cacheKey);
			//String json = (String) redisCache.get(cacheKey);
			return ResponseUtil.ok(JsonUtil.jsonToObject(json));
		}
		
		ExecutorService executorService = Executors.newFixedThreadPool(4);
		final long waitTime = 8 * 1000;
		final long awaitTime = 5 * 1000;

		// 学校
		Callable<LitemallSchool> schoolCallable = () -> schoolService.getOneSchool(schoolId);

		// 广告
		Callable<List> bannerListCallable = () -> adService.queryIndex();
		
		//九宫图
		Callable<List> categorySupport = () -> categorySupportService.queryL0(0, 50);
		//商家分类
		Callable<List> categoryMerchant = () -> categorySupportService.queryL1(0, 50);

		// 商家
		FutureTask<LitemallSchool> schoolTask = new FutureTask<>(schoolCallable);
		Callable<List> shopListCallable = () -> shopService.selectShoplist(schoolTask.get().getShopIds());

		Map<String, Object> entity = new HashMap<>();
		try {
			// Callable<List> newGoodsListCallable = () -> goodsService.queryByNew(0, 100);

			// List<LitemallGoods> newGoodsListCallable =
			// goodsService.queryByListGoodsId(productIds);

			// FutureTask<List> couponListTask = new FutureTask<>(couponListCallable);
			// FutureTask<List> newGoodsListTask = new FutureTask<>(newGoodsListCallable);

			// FutureTask<LitemallSchool> shoolTask = new FutureTask<>(schoolCallable);
			// FutureTask<List> newGoodsListTask = new FutureTask<>(newGoodsListCallable);

			FutureTask<List> bannerTask = new FutureTask<>(bannerListCallable);
			FutureTask<List> shopListTask = new FutureTask<>(shopListCallable);
			FutureTask<List> categoryIndexListTask = new FutureTask<>(categorySupport);
			FutureTask<List> categoryMerchantTask = new FutureTask<>(categoryMerchant);

			// executorService.submit(couponListTask);
			// executorService.submit(newGoodsListTask);
			// executorService.submit(newGoodsListTask);
			executorService.submit(schoolTask);
			executorService.submit(bannerTask);
			executorService.submit(shopListTask);
			executorService.submit(categoryIndexListTask);
			executorService.submit(categoryMerchantTask);

			entity.put("banner", bannerTask.get());
			entity.put("shop", shopListTask.get());
			entity.put("categoryIndex", categoryIndexListTask.get());
			entity.put("categoryMerchan", categoryMerchantTask.get());
			
			String BannerTop = systemConfigService.getbannerTop().get("litemall_wx_banner_top_A");
			String BannerAfter = systemConfigService.getbannerAfter().get("litemall_wx_banner_after_A");
			boolean Top = false;
			boolean After = false;
			
			if(!StringUtils.isEmpty(BannerTop)) {
				if(BannerTop.equals("true")) {
					Top = true;
				}
			}
			if(!StringUtils.isEmpty(BannerTop)) {
				if(BannerAfter.equals("true")) {
					After = true;
				}
			}
			
			entity.put("bannerOff1", Top);
			entity.put("bannerOff2", After);
			
			// 缓存数据
			//HomeCacheManager.loadData(cacheKey, entity);
			redisCache.setCacheObject(cacheKey, JsonUtil.mapToJson(entity));

		} catch (Exception e) {
			e.printStackTrace();
			entity.put("shop", null);
			// 终止所有线程
			executorService.shutdownNow();
		} finally {
			executorService.shutdown();
			try {
				if (!executorService.awaitTermination(awaitTime, TimeUnit.MILLISECONDS)) {
					executorService.shutdownNow();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return ResponseUtil.ok(entity);
	}

	private List<Map> getCategoryList() {
		List<Map> categoryList = new ArrayList<>();
		List<LitemallCategory> catL1List = categoryService.queryL1WithoutRecommend(0,
				SystemConfig.getCatlogListLimit());
		for (LitemallCategory catL1 : catL1List) {
			List<LitemallCategory> catL2List = categoryService.queryByPid(catL1.getId());
			List<Integer> l2List = new ArrayList<>();
			for (LitemallCategory catL2 : catL2List) {
				l2List.add(catL2.getId());
			}

			List<LitemallGoods> categoryGoods;
			if (l2List.size() == 0) {
				categoryGoods = new ArrayList<>();
			} else {
				categoryGoods = goodsService.queryByCategory(l2List, 0, SystemConfig.getCatlogMoreLimit());
			}

			Map<String, Object> catGoods = new HashMap<>();
			catGoods.put("id", catL1.getId());
			catGoods.put("name", catL1.getName());
			catGoods.put("goodsList", categoryGoods);
			categoryList.add(catGoods);
		}
		return categoryList;
	}

	/**
	 * 商城介绍信息
	 * 
	 * @return 商城介绍信息
	 */
	@GetMapping("/about")
	public Object about() {
		Map<String, Object> about = new HashMap<>();
		about.put("name", SystemConfig.getMallName());
		about.put("address", SystemConfig.getMallAddress());
		about.put("phone", SystemConfig.getMallPhone());
		about.put("qq", SystemConfig.getMallQQ());
		about.put("longitude", SystemConfig.getMallLongitude());
		about.put("latitude", SystemConfig.getMallLatitude());
		return ResponseUtil.ok(about);
	}
}